const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// 测试工具类
class TestUtils {
  // 生成测试用的JWT token
  static generateTestToken(userId = 1, role = 'user') {
    return jwt.sign(
      { userId, role },
      process.env.JWT_SECRET || 'test-secret',
      { expiresIn: '1h' }
    );
  }

  // 生成测试用户数据
  static getTestUser(overrides = {}) {
    return {
      id: 1,
      username: 'testuser',
      email: 'test@example.com',
      name: 'Test User',
      role: 'user',
      status: 'active',
      created_at: new Date(),
      ...overrides
    };
  }

  // 生成测试管理员数据
  static getTestAdmin(overrides = {}) {
    return this.getTestUser({
      id: 2,
      username: 'admin',
      email: 'admin@example.com',
      name: 'Admin User',
      role: 'admin',
      ...overrides
    });
  }

  // 生成加密的测试密码
  static async getHashedPassword(password = 'testpass123') {
    return await bcrypt.hash(password, 12);
  }

  // 验证密码
  static async verifyPassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
  }

  // 生成测试基金数据
  static getTestFund(overrides = {}) {
    return {
      id: 1,
      code: '000001',
      name: '测试基金',
      type: '股票型',
      manager: '测试经理',
      company: '测试公司',
      nav: 1.2345,
      nav_date: new Date(),
      risk_level: '中风险',
      ...overrides
    };
  }

  // 生成测试投资组合数据
  static getTestPortfolio(overrides = {}) {
    return {
      id: 1,
      name: '测试组合',
      description: '测试投资组合',
      user_id: 1,
      risk_level: '平衡型',
      target_return: 0.08,
      max_drawdown: 0.15,
      created_at: new Date(),
      ...overrides
    };
  }

  // 生成测试策略数据
  static getTestStrategy(overrides = {}) {
    return {
      id: 1,
      name: '测试策略',
      type: 'asset_allocation',
      description: '测试投资策略',
      user_id: 1,
      status: 'active',
      created_at: new Date(),
      ...overrides
    };
  }

  // 清理测试数据
  static async cleanupTestData(query) {
    try {
      // 清理测试用户
      await query('DELETE FROM users WHERE username LIKE "test%"');
      // 清理测试基金
      await query('DELETE FROM funds WHERE name LIKE "测试%"');
      // 清理测试组合
      await query('DELETE FROM portfolios WHERE name LIKE "测试%"');
      // 清理测试策略
      await query('DELETE FROM strategies WHERE name LIKE "测试%"');
    } catch (error) {
      console.error('清理测试数据失败:', error);
    }
  }

  // 设置测试环境
  static setupTestEnvironment() {
    // 设置测试环境变量
    process.env.NODE_ENV = 'test';
    process.env.JWT_SECRET = 'test-secret-key';
    process.env.JWT_EXPIRES_IN = '1h';
  }

  // 重置测试环境
  static resetTestEnvironment() {
    delete process.env.NODE_ENV;
    delete process.env.JWT_SECRET;
    delete process.env.JWT_EXPIRES_IN;
  }
}

module.exports = TestUtils; 